<template>
  <div class="comment-list">
    <div :key="item.id" class="comment-item" v-for="item in commentList">
      <div class="cm-user-info-part">
        <img :src="item.author.avatar" class="cm-avatar"/>
        <span class="cm-nickname" v-text="item.author.nickname"></span>
      </div>
      <div class="cm-content-part">
        <!--评论操作区域-->
        <div class="cm-action-part">
          <span v-text="item.created_date" class="cm-date"></span>
          <span
              class="cm-comment-response el-icon-chat-round"
              @click="toggleReplyInput(item.id, item.author.id)"
          >
            <i class="fa fa-comment"></i> 回复
          </span>

        </div>
        <!-- 评论内容 -->
        <div class="cm-content">
          <p v-html="item.content"></p>
        </div>
        <!-- 子评论列表 -->
        <div class="cm-sub-comment-list" v-if="item.children && item.children.length"> <!-- 添加展开/收起按钮 -->
          <div v-for="subItem in showSubComments(item)" :key="subItem.id" class="cm-sub-comment-item">
            <div class="cm-user-info-part">
              <img :src="subItem.author.avatar" class="cm-avatar"/>
              <span class="cm-nickname" v-text="subItem.author.nickname"></span>
            </div>
            <div class="cm-sub-content-part">
              <div class="cm-action-part">
                <span v-text="subItem.created_date" class="cm-date"></span>
                <!-- 子评论的回复按钮 -->
                <span class="cm-comment-response el-icon-chat-round"
                      @click="toggleReplyInput(subItem.id, subItem.author.id)">
                  <i class="fa fa-comment"></i> 回复
                </span>
              </div>
              <div class="cm-content">
                <span v-if="subItem.parent_author"><i class="fa fa-share"></i> @{{ subItem.parent_author }}：</span>
                <span v-html="subItem.content"></span>
              </div>
              <!-- 子评论回复输入框 -->
            </div>
            <div :id="`cm-input-${subItem.id}`" class="cm-input-box" v-show="activeReplyId === subItem.id">
              <div v-if="replyTarget && replyTarget.nickname" class="cm-reply-target">回复 @{{
                  replyTarget.nickname
                }}：
              </div>
              <div :id="`editor-${subItem.id}`" class="cm-editor-container"></div>
              <div class="cm-reply-actions">
                <button @click="cancelReply">取消</button>
                <button type="primary" @click="submitReply(subItem)">提交</button>
              </div>
            </div>
          </div>
          <div v-if="item.children.length > 3" class="cm-expand-toggle">
            <button @click="toggleExpand(item.id)" class="cm-expand-button">
              {{ expandedParents[item.id] ? '收起' : `展开剩余 ${item.children.length - 3} 条回复` }}
              <i :class="[`fa fa-${expandedParents[item.id] ? 'angle-up' : 'angle-down'}`]"></i>
            </button>
          </div>
        </div>
        <!-- 父评论回复输入框 -->
        <div :id="`cm-input-${item.id}`" class="cm-input-box" v-show="activeReplyId === item.id">
          <div v-if="replyTarget && replyTarget.nickname" class="cm-reply-target">回复 @{{
              replyTarget.nickname
            }}：
          </div>
          <div :id="`editor-${item.id}`" class="cm-editor-container"></div>
          <div class="cm-reply-actions">
            <button @click="cancelReply">取消</button>
            <button type="primary" @click="submitReply(item)">提交</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页控制 -->
    <div class="cm-has-more" v-if="hasMore" @click="loadMore">>>> 加载更多 >>></div>
    <div class="cm-no-more" v-else>---- 我是有底线的 ----</div>
  </div>
</template>
<script setup>
import E from 'wangeditor'

const editorInstances = ref({}) // 存储编辑器实例
const commentList = ref([])
const hasMore = ref(true)
const activeReplyId = ref(null)// 当前激活的回复ID
const replyContents = ref({}) // 修改为对象存储各编辑器内容
const replyTarget = ref(null)  // 新增：记录回复目标
const currentParentId = ref(null)  // 新增：记录当前父级ID
const currentPage = ref(1)// 当前页码
const pageSize = ref(15) // 需要和后端分页设置保持一致
const expandedParents = ref({});

const showSubComments = (item) => {
  return expandedParents.value[item.id]
      ? item.children
      : item.children.slice(0, 3);
};
const toggleExpand = (parentId) => {
  expandedParents.value[parentId] = !expandedParents.value[parentId];
};
// 修改后的统一初始化方法
const initEditor = (commentId) => {
  // 确保DOM已更新
  nextTick(() => {
    // 清理旧实例
    if (editorInstances.value[commentId]) {
      editorInstances.value[commentId].destroy();
    }
    // 创建新实例
    const editor = new E(`#editor-${commentId}`);
    editor.config.placeholder = '请输入评论内容...';
    editor.config.onChange = (html) => {
      if (activeReplyId.value === commentId) {
        replyContent.value = html; // 更新当前激活编辑器的内容
      }
    };
    editor.config.menus = ['bold', 'italic', 'underline', 'link', 'list', 'emoticon'];
    editor.create();
    editorInstances.value[commentId] = editor;
  });
};
// 销毁编辑器方法
const destroyEditor = (commentId) => {
  const editor = editorInstances.value[commentId];
  if (editor) {
    editor.destroy();
    delete editorInstances.value[commentId];
  }
};
// 获取根评论
const fetchComments = async (page = 1) => {
  const scrollPosition = window.scrollY || document.documentElement.scrollTop;
  try {
    const response = await axios.get('/api/comments/comments/get_root_comments/', {
      params: {
        page: page
      }
    });
    const comments = response.data.results.map(c => ({
      ...c,
      children: c.children || [],
      author: c.author ?? {}, // 默认值处理，防止 `author` 为 null 或 undefined
    }));
    // 如果是第一页则重置数据，否则合并数据
    if (page === 1) {
      commentList.value = comments
    } else {
      commentList.value = [...commentList.value, ...comments]
    }
    // 更新分页状态
    hasMore.value = !!response.data.next
    await nextTick();
    window.scrollTo(0, scrollPosition);
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};
// 新增加载更多方法
const loadMore = () => {
  currentPage.value += 1
  fetchComments(currentPage.value)
}
// 新增强制刷新方法
const forceRefresh = async () => {
  await nextTick()
  commentList.value = [...commentList.value]
}
// 显示/隐藏回复框
const toggleReplyInput = (commentId, authorId) => {
  if (activeReplyId.value === commentId) {
    // 隐藏当前激活的回复框
    replyTarget.value = null;
    currentParentId.value = null;
    destroyEditor(commentId);
    replyContents.value = ''; // 清空内容
  } else {
    nextTick(() => {
      initEditor(commentId);
    });

    const targetComment = findComment(commentList.value, commentId);
    replyTarget.value = {
      id: authorId,
      nickname: targetComment?.author?.nickname,
    };
    currentParentId.value = targetComment?.parent || commentId; // 设置父级ID
  }

  activeReplyId.value = activeReplyId.value === commentId ? null : commentId;
};
// 子评论回复处理
const handleSubReply = (parentId, comment) => {
  activeReplyId.value = parentId
  replyTarget.value = {
    id: comment.id,
    nickname: comment.author.nickname
  }
  currentParentId.value = parentId
}
// 提交回复
const submitReply = async (parentComment) => {
  const editor = editorInstances.value[activeReplyId.value];
  const content = editor?.txt?.html().trim();

  if (!content) {
    alert('回复内容不能为空');
    return;
  }

  try {
    const payload = {
      content,
      article: parentComment.article,
      parent: currentParentId.value,
    };

    if (replyTarget.value) {
      payload.parent_author = replyTarget.value.nickname;
    }

    const response = await axios.post('/api/comments/comments/', payload, { requiresAuth: true },{
      headers: {'X-Full-Data': 'true'},
    });

    // 确保 `response.data.author` 不为空，默认给出空对象
    const newComment = {
      ...response.data,
      author: response.data.author ?? {}, // 确保 `author` 存在，防止为空
    };

    // 更新评论数据
    if (currentParentId.value) {
      commentList.value = updateChildren(commentList.value)(currentParentId.value, newComment);
    } else {
      commentList.value = commentList.value.map((comment) =>
          comment.id === parentComment.id
              ? {...comment, children: [...(comment.children || []), newComment]}
              : comment
      );
    }

    // 强制DOM更新
    await nextTick();
  } catch (error) {
    console.error('回复失败:', error);
    await fetchComments();
  } finally {
    cancelReply();
  }
};
// 更新子评论的方法
const updateChildren = (comments) => (parentId, newComment) =>
    comments.map((comment) => ({
      ...comment,
      children: comment.id === parentId
          ? [...(comment.children || []), {...newComment, author: newComment.author ?? {}}]
          : comment.children && updateChildren(comment.children)(parentId, newComment),
    }));

// 查找评论的递归方法
const findComment = (comments, targetId) =>
    comments.reduce((found, comment) => {
      if (found) return found;
      if (comment.id === targetId) return comment;
      return comment.children && findComment(comment.children, targetId);
    }, null);
const cancelReply = () => {
  Object.keys(editorInstances.value).forEach((id) => destroyEditor(id)); // 销毁所有编辑器实例
  activeReplyId.value = null; // 清空当前激活的回复框 ID
  replyContents.value = ''; // 清空回复框内容
  replyTarget.value = null; // 清空回复目标
  currentParentId.value = null; // 清空当前父级 ID
};

defineExpose({
  fetchComments,
});

onMounted(() => {
  currentPage.value = 1;
  fetchComments();
});

onBeforeUnmount(() => {
  Object.keys(editorInstances.value).forEach((id) => destroyEditor(id));
});
</script>
<style scoped>
/* 最外层容器 */
.comment-list {
  background: var(--card-bg-color,#fff);
}

/* 评论项容器 */
.comment-item {
  padding: 5px 20px;
}

/* 用户信息区域 */
.cm-user-info-part {
  line-height: 40px;
}
.cm-user-info-part .cm-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  vertical-align: middle !important;
}
.cm-user-info-part .cm-nickname {
  font-size: 16px;
  font-weight: 600;
  margin-left: 5px;
  margin-right: 5px;
}
.cm-user-info-part .cm-position,
.cm-user-info-part .cm-company {
  font-size: 13px;
}
/* 内容区域 */
.cm-content-part {
  margin-left: 40px;
}
.cm-content {
  font-size: 14px;
  margin-top: 10px;
  color: #333;
  line-height: 1.5;
}
/* 操作区域 */
.cm-action-part {
  display: flex;
  align-items: center;
  font-size: 14px;
  gap: 10px;
  color: #686464;
}
/* 日期 */
.cm-date {
  font-size: 14px;
  flex: 1;
}
/* 评论回复按钮 */
.cm-comment-response {
  cursor: pointer;
  font-size: 12px;
  color: #686464;
}
.cm-comment-response:hover {
  opacity: .8;
}
/* 子评论项样式 */
.cm-sub-comment-list {
  padding: 20px;
  margin-top: 10px;
  background: #fafbfc;
  border-left: 2px solid #eee;
}
.cm-sub-comment-item .cm-user-info-part {
  line-height: 30px;
}
.cm-sub-comment-item .cm-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  vertical-align: middle !important;
}
.cm-sub-comment-item .cm-nickname {
  font-size: 14px;
  font-weight: 600;
  margin-left: 5px;
  margin-right: 5px;
}
.cm-sub-content-part {
  margin-left: 40px;
  margin-bottom: 10px;
}
.cm-expand-toggle {
  text-align: center;
  margin-top: 10px;
}
.cm-expand-button {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 5px 10px;
  font-size: 14px;
  transition: opacity 0.3s;
}
.cm-expand-button:hover {
  opacity: 0.8;
}
/* 回复输入框 */
.cm-reply-target {
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  padding: 4px 0;
}
/* 重构回复输入框 */
.cm-input-box {
  margin-top: 15px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
}
/* 新增编辑器容器样式 */
.cm-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  margin: 8px 0;
}
/* 调整输入框高度 */
.cm-editor-container .w-e-text-container {
  min-height: 80px !important;
}
/* 移除原来的textarea样式 */
.cm-reply-box {
  display: none;
}
/* 覆盖wangEditor默认样式 */
:deep(.w-e-text-container) {
  min-height: 60px !important;
  max-height: 120px;
  overflow-y: auto;
}
:deep(.w-e-toolbar) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 5px;
}
:deep(.w-e-menu) {
  padding: 5px 8px;
}
.cm-reply-box:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 4px rgba(64, 158, 255, 0.2);
}
/* 美化操作按钮 */
.cm-reply-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.cm-reply-actions button {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}
/* 取消按钮样式 */
.cm-reply-actions button:first-child {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}
.cm-reply-actions button:first-child:hover {
  border-color: #409eff;
  color: #409eff;
}
/* 提交按钮样式 */
.cm-reply-actions button[type="primary"] {
  background: #409eff;
  border: none;
  color: white;
}
.cm-reply-actions button[type="primary"]:hover {
  background: #66b1ff;
}
.cm-reply-actions button[type="primary"]:active {
  background: #337ecc;
}
/* 加载更多 */
.cm-has-more,
.cm-no-more {
  text-align: center;
  padding: 10px;
  color: #999999;
}
.cm-has-more {
  cursor: pointer;
}
.cm-has-more:hover {
  opacity: .6;
}
</style>
